package com.atstudy;

import com.atstudy.proxy.Agent;
import com.atstudy.proxy.AgentImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/2/14 9:49
 * @copyright: 博为峰
 */
public class Test {
    public static void main(String[] args) {
        final AgentImpl agent = new AgentImpl();
//        agent.sale(1000);
//        agent.service();

        //jdk 创建代理对象的方式
        Agent proxyInstance = (Agent) Proxy.newProxyInstance(agent.getClass().getClassLoader(), agent.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                int money = (int) args[0];
                if (method.getName().equals("sale")) {
                    //前置通知
                    money = money / 2;
                    try {
                        method.invoke(agent, money);
                        //后置通知
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                        //异常通知
                    } finally {
                        //最终通知
                    }
                    //操作
                } else if (method.getName().equals("service")) {
                    //操作
                    method.invoke(agent);
                }
                return null;
            }
        });

        proxyInstance.sale(1000);
//        proxyInstance.service();
    }
}
